package com.lixin.smartclassroom.ui.home.tab1.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import com.drake.brv.utils.bindingAdapter
import com.drake.channel.receiveEvent
import com.drake.channel.sendEvent
import com.drake.net.utils.scopeNetLife
import com.drake.tooltip.toast
import com.google.zxing.integration.android.IntentIntegrator
import com.lixin.smartclassroom.R
import com.lixin.smartclassroom.api.bannerlist
import com.lixin.smartclassroom.api.bindstudentlist
import com.lixin.smartclassroom.api.courselist
import com.lixin.smartclassroom.api.customerdetail
import com.lixin.smartclassroom.api.getmessagecount
import com.lixin.smartclassroom.api.jingcailist
import com.lixin.smartclassroom.api.noticedetail
import com.lixin.smartclassroom.api.noticelist
import com.lixin.smartclassroom.bean.AnnouncementBean
import com.lixin.smartclassroom.bean.DataListBean
import com.lixin.smartclassroom.databinding.FragmentTab1Binding
import com.lixin.smartclassroom.ext.child_id
import com.lixin.smartclassroom.ext.child_name
import com.lixin.smartclassroom.ext.user_image
import com.lixin.smartclassroom.ext.user_name
import com.lixin.smartclassroom.ext.user_role
import com.lixin.smartclassroom.ui.WebHtmlActivity
import com.lixin.smartclassroom.ui.home.adapter.ImageBannerAdapter
import com.lixin.smartclassroom.ui.home.adapter.MyBannerAdapter
import com.lixin.smartclassroom.ui.home.adapter.courseClass
import com.lixin.smartclassroom.ui.home.adapter.excitingMoment
import com.lixin.smartclassroom.ui.home.tab1.activity.CourseDetailAct
import com.lixin.smartclassroom.ui.home.tab1.activity.CourseRecommendAct
import com.lixin.smartclassroom.ui.home.tab1.activity.ExcitingMomentDetailAct
import com.lixin.smartclassroom.ui.home.tab1.activity.ExcitingMomentsAct
import com.lixin.smartclassroom.ui.home.tab1.activity.MessageAct
import com.lixin.smartclassroom.ui.home.tab1.activity.SearchAct
import com.lixin.smartclassroom.ui.home.tab4.activity.YanXueDetailAct
import com.lixin.smartclassroom.ui.home.tab5.activity.CaptureAct
import com.lixin.smartclassroom.ui.home.tab5.activity.ScanResultAct
import com.lixin.smartclassroom.ui.login.BindStudentAct
import com.lixin.smartclassroom.utils.LoginManager
import com.lixinkeji.activity.WebActivity
import com.lixinkeji.base.BaseFragment
import com.lixinkeji.extension.dp2px
import com.lixinkeji.extension.loadCircle
import com.lixinkeji.extension.loadRound
import com.lixinkeji.extension.onClick
import com.lixinkeji.extension.removeAt
import com.lixinkeji.extension.setRoundRectBg
import com.lixinkeji.extension.start
import com.lixinkeji.extension.toast
import com.lixinkeji.extension.uId
import com.lixinkeji.extension.visible

/**
 * Description
 * Author: lwc
 * Date:2023/12/5 15:14
 */
class Tab1Fragment : BaseFragment<FragmentTab1Binding>() {
    override fun getViewBinding(
        inflater: LayoutInflater, container: ViewGroup?
    ) = FragmentTab1Binding.inflate(inflater)

    //user_role  //1--家长  2学生   3老师
    private var listBeans = ArrayList<DataListBean>()


    override fun iniView() {

        binding.apply {

            tvBindStudent.setRoundRectBg(
                Color.parseColor("#4B6AEF"), requireActivity().dp2px(17f).toInt()
            )
            tvSearch.setRoundRectBg(
                Color.parseColor("#FFFFFF"), requireActivity().dp2px(17f).toInt()
            )
            initImgBanner()
            initBanner()
            llAnnouncement.setRoundRectBg(
                Color.parseColor("#FFFFFF"), requireActivity().dp2px(22f).toInt()
            )

            getExcitingMomentsData()
            getCourseRecommendData()

            rcvExcitingMoments.excitingMoment().apply {
                R.id.btnDelete.onClick {
                    rcvExcitingMoments.bindingAdapter.removeAt(modelPosition)
                }

                R.id.rl.onClick {
                    context.start(ExcitingMomentDetailAct::class.java) {
                        putExtra("jingcaiid", (models?.get(modelPosition) as DataListBean).id)
                    }
                }

            }.models = listBeans

        }

        receiveEvent<String>("showMessageCount") {
            binding.tvMessageCount.visible()
            binding.tvMessageCount.text = it
        }

    }

    private fun getBindStudentData() {
        scopeNetLife {
            val listBean = bindstudentlist(1, 1000)!!
            if (listBean != null && listBean.size > 0) {
                binding.tvBindStudent.text = listBean[0].name
                requireContext().child_id = listBean[0].id.toString()
                requireContext().child_name = listBean[0].name.toString()

            } else {
                binding.tvBindStudent.text = "绑定学生"
            }
        }
    }

    private fun getCustomerdetail() {
        scopeNetLife {
            var baseBean = customerdetail()
            if (baseBean.result == "0") {
                binding.apply {
                    requireContext().user_name = baseBean.name.toString()
                    requireContext().user_image = baseBean.image.toString()
                    requireContext().uId = baseBean.id.toString()

                    tvName.text = baseBean.name
                    when (baseBean.jieduan) {
                        "1" -> tvStudentGrade.text = "小学"
                        "2" -> tvStudentGrade.text = "初中"
                        "3" -> tvStudentGrade.text = "高中"
                        "4" -> tvStudentGrade.text = "大学"
                    }

                    if (baseBean.image != null)
                        headImg.loadCircle(baseBean.image!!)
                }
            } else if (baseBean.result == "-2") {
                toast(baseBean.resultNote.toString())
                LoginManager.logout(requireActivity())
            }
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        if (!hidden) {
            scopeNetLife {
                val baseBean = getmessagecount()
                if (baseBean.result == "0") {
                    if (baseBean.count?.isNotEmpty() == true && baseBean.count != "0")
                        sendEvent(baseBean.count.toString(), "showMessageCount")
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        getCustomerdetail()
        binding.apply {
            when (requireActivity().user_role) {
                1 -> {
                    tvBindStudent.visible()
                    tvSearch.visible()
                    if (requireContext().child_id.isEmpty())
                        getBindStudentData()
                    else
                        tvBindStudent.text = requireContext().child_name
                }

                2 -> {
                    tvStudentGrade.visible()
                    tvSearch.visible()
                }

                3 -> {
                    tvName.visible()
                    headImg.visible()
                    imgSearch.visible()

                }
            }
        }
    }

    private fun getExcitingMomentsData() {
        scopeNetLife {
            val dataListBean = jingcailist(1, 10, "1")!!
            binding.rcvExcitingMoments.excitingMoment().apply {
                R.id.btnDelete.onClick {
                    binding.rcvExcitingMoments.bindingAdapter.removeAt(modelPosition)
                }

                R.id.rl.onClick {
                    context.start(ExcitingMomentDetailAct::class.java) {
                        putExtra("jingcaiid", (models?.get(modelPosition) as DataListBean).id)
                    }
                }
            }.models = dataListBean
        }
    }

    @SuppressLint("SetTextI18n")
    private fun getCourseRecommendData() {
        scopeNetLife {
            val dataListBean = courselist(1, 5, "1").dataList
            binding.apply {
                if (dataListBean != null) {
                    if (dataListBean.size > 0) {
                        img.loadRound(dataListBean[0].coverimage!!, 10, true)
                        tvTime.text = dataListBean[0].createdate!!
                        tvTitle.text = dataListBean[0].title!!
                        tvLookNum.text = dataListBean[0].seecount!! + "位同学观看"

                        rlFirst.onClick {
                            start(CourseDetailAct::class.java) {
                                putExtra("courseid", dataListBean[0].id)
                            }
                        }

                        binding.rcvRecommend.courseClass().models =
                            dataListBean.subList(1, dataListBean.size)
                    }
                }

            }

        }

    }

    /**
     *@Description 图片轮播
     *@date 创建时间2024/1/3
     *
     */
    private fun initImgBanner() {
        scopeNetLife {
            val dataList = bannerlist()
            val adapter = ImageBannerAdapter(context, dataList)
            binding.imgBanner.setAdapter(adapter)
            binding.imgBanner.addBannerLifecycleObserver(requireActivity())
            binding.imgBanner.scrollTime = 2000
            binding.imgBanner.start()
            adapter.setOnBannerListener { _, position ->
                if (dataList?.get(position)?.projectid?.isNotEmpty() == true) {
                    when (dataList?.get(position)!!.type) {
                        "1" -> start(YanXueDetailAct::class.java) {
                            putExtra("type", "3")
                            putExtra("courseid", dataList[position].projectid)
                        }

                        "2" -> start(ExcitingMomentDetailAct::class.java) {
                            putExtra("jingcaiid", dataList[position].projectid)
                        }
                    }
                }

            }
        }

    }

    /**
     *@Description 公告轮播
     *@date 创建时间2024/1/3
     *
     */
    private fun initBanner() {
        scopeNetLife {
            val baseBean = noticelist(1, 1000)
            if (baseBean.result == "0") {
                val dataList = baseBean.data
                if (dataList != null && dataList.size > 0) {
                    val adapter = MyBannerAdapter(context, dataList)
                    binding.banner.setAdapter(adapter)
                    binding.banner.addBannerLifecycleObserver(requireActivity())
                    binding.banner.scrollTime = 2000
                    binding.banner.start()
                    adapter.setOnBannerListener { _, position ->

                        scopeNetLife {
                            val baseBean = noticedetail(dataList[position].id!!)
                            if (baseBean.result == "0") {
                                start(WebHtmlActivity::class.java) {
                                    putExtra("title", baseBean.title)
                                    putExtra("url", baseBean.content)
                                    putExtra("type", 4)
                                }
                            } else if (baseBean.result == "-2") {
                                toast(baseBean.resultNote.toString())
                                LoginManager.logout(requireActivity())
                            } else {
                                toast(baseBean.resultNote)

                            }
                        }
                    }
                }
            }
        }
    }

    override fun onClick() {
        binding.apply {
            tvBindStudent.onClick {
                start(BindStudentAct::class.java) {
                    if (requireContext().child_id.isEmpty())
                        putExtra("bindType", "1")
                    else
                        putExtra("bindType", "2")
                    putExtra("type", "1")
                }
            }
            rlMessage.onClick {
                start(MessageAct::class.java)
            }
            btnMoreRecommend.onClick {
                start(CourseRecommendAct::class.java)
            }

            btnMoreMoments.onClick {
                start(ExcitingMomentsAct::class.java)
            }
            tvSearch.onClick {
                start(SearchAct::class.java)
            }
            imgSearch.onClick {
                start(SearchAct::class.java)
            }

            imgSacn.onClick {
                val integrator = IntentIntegrator(requireActivity())
                // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
                // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)
                integrator.captureActivity = CaptureAct::class.java
                integrator.setPrompt("扫描条码")
                integrator.setOrientationLocked(false)
                integrator.setCameraId(0) // 使用默认的相机

                integrator.setBeepEnabled(false) // 扫到码后播放提示音

                integrator.setBarcodeImageEnabled(true)
                integrator.initiateScan()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            if (result.contents == null) {
                toast("Cancelled")

            } else {
                val content = result.contents
                toast("content")

                // TODO:添加跳转课程逻辑
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

}